﻿using Liju.Common;
using Liju.Model;
using LiJu.Db;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace LiJu.Record
{
    public partial class ProductRecord : UserControl
    {
        /// <summary>
        /// 记录表格默认字体
        /// </summary>
        private Font defaultFont = new Font("Microsoft YaHei", 9);

        /// <summary>
        /// 所有产品数据
        /// </summary>
        List<ProductRecordModel> ProductRecordData = new List<ProductRecordModel>();

        /// <summary>
        /// 产品名称数据
        /// </summary>
        List<string> ProudctNameData = new List<string>();

        /// <summary>
        /// 产品条码数据
        /// </summary>
        List<string> BarcodeData = new List<string>();

        /// <summary>
        /// 测试状态类型
        /// </summary>
        Dictionary<int, string> TestStatus = new Dictionary<int, string>()
        {
            {0,"未开始" },
            {1,"完成" },
            {2,"执行中" },
            {3,"NG" }
        };
        public ProductRecord()
        {
            InitializeComponent();

            historyRecordButton.HistoryRecordAction += ChangeHistoryRecord;
            gdview_RecordList.CellMouseEnter += gdview_RecordList_CellMouseEnter;
            gdview_RecordList.CellMouseLeave += gdview_RecordList_CellMouseLeave;
            gdview_RecordList.CellFormatting += Gdview_RecordList_CellFormatting;
            ResetData();
        }
        /// <summary>
        /// 登录加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductRecord_Load(object sender, EventArgs e)
        {
            InitData();
            bnt_Search_Click(null, null);
        }

        #region 方法

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitData()
        {
            ResetData();

            //查询所有可用产品
            ProductRecordData = ProductRecordDbHelper.GetAllProductRecords();
            //最新十条产品名称模糊搜索
            ProudctNameData = ProductRecordData.OrderByDescending(o => o.ProductRecordID).Select(c => c.ProductName).Distinct().Take(10).ToList();
            this.txt_ProductName.AutoCompleteCustomSource.Clear();
            this.txt_ProductName.AutoCompleteCustomSource.AddRange(ProudctNameData.ToArray());
            this.txt_ProductName.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            this.txt_ProductName.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
            //最新十条条码模糊搜索
            BarcodeData = ProductRecordData.OrderByDescending(o => o.ProductRecordID).Select(c => c.ProductSN).Distinct().Take(10).ToList();
            this.txt_Barcode.AutoCompleteCustomSource.Clear();
            this.txt_Barcode.AutoCompleteCustomSource.AddRange(BarcodeData.ToArray());
            this.txt_Barcode.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            this.txt_Barcode.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;

            //产品完成状态选项
            List<string> statusScources = new List<string>();
            foreach (string status in TestStatus.Values)
            {
                statusScources.Add(status);
            }
            cbx_FinishStatus.DataSource = statusScources;// TestStates;
            cbx_FinishStatus.Text = null;

            //表格只读，不可修改
            gdview_RecordList.ReadOnly = true;
            //列标题居中
            gdview_RecordList.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //单元格字体居中显示
            gdview_RecordList.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //显示行网格线，隐藏列网格线
            this.gdview_RecordList.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;
            this.gdview_RecordList.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.gdview_RecordList.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            // 设置选中单元格的背景颜色
            gdview_RecordList.DefaultCellStyle.SelectionBackColor = System.Drawing.ColorTranslator.FromHtml("#BFEFFF");
            //设置选择模式为整行选择
            gdview_RecordList.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //// 设置选中单元格的前景颜色
            //gdview_RecordList.DefaultCellStyle.SelectionForeColor = Color.Black;
            gdview_RecordList.RowTemplate.Height = 35;
            this.gdview_RecordList.DefaultCellStyle.Font = defaultFont;
            ////datetimepicker显示日期和时间
            //dt_WorkStartTime.CustomFormat = "yyyy-MM-dd HH:mm:ss";
            //dt_WorkStartTime.Format = DateTimePickerFormat.Custom;
            //dt_WorkStartTime.ShowUpDown = false;

            // 假设你的DataGridView控件名为dataGridView1

            // 创建一个新的Font对象
            Font columnFont = new Font("Microsoft YaHei", 12, FontStyle.Bold);
            // 设置列头的默认单元格样式
            gdview_RecordList.ColumnHeadersDefaultCellStyle.Font = columnFont;

        }

        /// <summary>
        /// 重置数据
        /// </summary>
        public void ResetData()
        {
            ResetProductAndBarcode();
            cbx_FinishStatus.Text = null;
            historyRecordButton.ResetStatus();
            ChangeHistoryRecord(HistoryRecordType.Today);

            lbl_ProductSum.Text = null;
            lbl_TaskSum.Text = null;
            lbl_UnfinishSum.Text = null;
            lbl_PassNum.Text = null;
            gdview_RecordList.Rows.Clear();
        }


        /// <summary>
        /// 重置产品名称和条码
        /// </summary>
        public void ResetProductAndBarcode()
        {
            txt_ProductName.Text = null;
            txt_Barcode.Text = null;
            hasProductName = false;
            hasBarcode = false;
            txt_ProductName_Leave(null, null);
            txt_Barcode_Leave(null, null);
        }

        /// <summary>
        /// 修改搜索日期
        /// </summary>
        /// <param name="historyRecordType"></param>
        private void ChangeHistoryRecord(HistoryRecordType historyRecordType)
        {
            if (historyRecordType == HistoryRecordType.Today)
            {
                dt_WorkStartTime.Value = DateTime.Now;
                dt_WorkEndTime.Value = DateTime.Now;
            }
            else if (historyRecordType == HistoryRecordType.Yesterday)
            {
                dt_WorkStartTime.Value = DateTime.Now.AddDays(-1);
                dt_WorkEndTime.Value = DateTime.Now.AddDays(-1);
            }
            else if (historyRecordType == HistoryRecordType.Last30Day)
            {
                dt_WorkStartTime.Value = DateTime.Now.AddDays(-30);
                dt_WorkEndTime.Value = DateTime.Now;
            }
            else if (historyRecordType == HistoryRecordType.Last90Day)
            {
                dt_WorkStartTime.Value = DateTime.Now.AddDays(-90);
                dt_WorkEndTime.Value = DateTime.Now;
            }
        }
        #endregion


        #region 产品名文本框提示
        bool hasProductName = false;//判断输入框是否有文本 
        private void txt_ProductName_Enter(object sender, EventArgs e)
        {
            if (hasProductName == false)
                txt_ProductName.Text = "";

            txt_ProductName.ForeColor = Color.Black;
        }

        private void txt_ProductName_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_ProductName.Text))
            {
                txt_ProductName.Text = "请输入";
                txt_ProductName.ForeColor = Color.LightGray;
                hasProductName = false;
            }
            else
                hasProductName = true;
        }
        #endregion

        #region 条码文本框提示
        bool hasBarcode = false;//判断输入框是否有文本 
        private void txt_Barcode_Enter(object sender, EventArgs e)
        {
            if (hasBarcode == false)
                txt_Barcode.Text = "";

            txt_Barcode.ForeColor = Color.Black;
        }

        private void txt_Barcode_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_Barcode.Text))
            {
                txt_Barcode.Text = "请输入";
                txt_Barcode.ForeColor = Color.LightGray;
                hasBarcode = false;
            }
            else
                hasBarcode = true;
        }
        #endregion


        /// <summary>
        /// 查询记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bnt_Search_Click(object sender, EventArgs e)
        {
            string productName = txt_ProductName.Text == "请输入" ? null : txt_ProductName.Text.Trim();
            string barcode = txt_Barcode.Text == "请输入" ? null : txt_Barcode.Text.Trim();
            string finishStatus = cbx_FinishStatus.Text;
            DateTime startTime = Convert.ToDateTime(dt_WorkStartTime.Text);
            DateTime endTime = Convert.ToDateTime(dt_WorkEndTime.Text).AddDays(1).AddSeconds(-1);
            HistoryRecordType historyRecordType = historyRecordButton.historyRecordType;

            ProductRecordData = ProductRecordDbHelper.GetAllProductRecords();
            List<ProductRecordModel> productrecords = ProductRecordData;

            lbl_ProductSum.Text = null;
            lbl_TaskSum.Text = null;
            lbl_UnfinishSum.Text = null;
            lbl_PassNum.Text = null;
            gdview_RecordList.Rows.Clear();

            if (!string.IsNullOrEmpty(productName))
            {
                productrecords = ProductRecordData.FindAll(o => o.ProductName.Contains(productName));
            }

            if (!string.IsNullOrEmpty(barcode))
            {
                productrecords = productrecords.FindAll(o => o.ProductSN.StartsWith(barcode));
            }

            if (!string.IsNullOrEmpty(finishStatus))
            {
                int status = 0;
                foreach (var keyValue in TestStatus)
                {
                    if (keyValue.Value.Equals(finishStatus))
                    {
                        status = keyValue.Key;
                    }

                }
                //TestStatus.TryGetValue(finishStatus,out)
                //if (finishStatus.Equals("未开始"))
                //{
                //    status = 0;
                //}
                //else if (finishStatus.Equals("完成"))
                //{
                //    status = 1;
                //}
                //else if (finishStatus.Equals("执行中"))
                //{
                //    status = 2;
                //}
                //else if (finishStatus.Equals("NG"))
                //{
                //    status = 3;
                //}
                if (status >= 0)
                {
                    productrecords = productrecords.FindAll(o => o.State == status);
                }

            }
            productrecords = productrecords.FindAll(o => o.CreateTime >= startTime && o.CreateTime <= endTime);

            //var productRecordGroup = productrecords.GroupBy(g => g.ProductSN).Select(g => g.ToList());
            //var recordList = new List<ProductRecordModel>();
            //foreach (var group in productRecordGroup)
            //{
            //    recordList.Add(group[0]);
            //}

            gdview_RecordList.Rows.Clear();
            for (int i = 0; i < productrecords.Count; i++)
            {
                ProductRecordModel productrecord = productrecords[i];
                // 添加一行数据
                gdview_RecordList.Rows.Add();
                // 为这行的各列赋值
                gdview_RecordList.Rows[i].Cells["Index"].Value = i + 1;
                gdview_RecordList.Rows[i].Cells["ProductName"].Value = productrecord.ProductName;
                gdview_RecordList.Rows[i].Cells["BarCode"].Value = productrecord.ProductSN;
                gdview_RecordList.Rows[i].Cells["WorkTime"].Value = productrecord.CreateTime;
                gdview_RecordList.Rows[i].Cells["ProductImgNum"].Value = productrecord.ImgNum;
                gdview_RecordList.Rows[i].Cells["TaskNum"].Value = productrecord.TaskNum;
                string result = null;
                // 0未开始 1完成 2执行中 3NG
                if (productrecord.State == 0)
                {
                    result = "未开始";
                    gdview_RecordList.Rows[i].Cells["Result"].Style.ForeColor = Color.Gray;
                }
                else if (productrecord.State == 1)
                {
                    result = "完成";
                    gdview_RecordList.Rows[i].Cells["Result"].Style.ForeColor = Color.Green;
                }
                else if (productrecord.State == 2)
                {
                    result = "执行中";
                    gdview_RecordList.Rows[i].Cells["Result"].Style.ForeColor = Color.Orange;
                }
                else if (productrecord.State == 3)
                {
                    result = "NG";
                    gdview_RecordList.Rows[i].Cells["Result"].Style.ForeColor = Color.Red;

                }
                gdview_RecordList.Rows[i].Cells["Result"].Value = result;
                gdview_RecordList.Rows[i].Cells["Operater"].Value = productrecord.UserName;
            }
            int recordCount = productrecords.Count;
            int sumTask = productrecords.Sum(c => c.TaskNum);
            int unFinishNum = productrecords.FindAll(o => o.State == 3).Count;
            float passNum = recordCount == 0 ? 0 : (float)productrecords.FindAll(o => o.State == 1).Count / recordCount;

            lbl_ProductSum.Text = recordCount.ToString();
            lbl_TaskSum.Text = sumTask.ToString();
            lbl_UnfinishSum.Text = unFinishNum.ToString();
            lbl_PassNum.Text = (passNum * 100.0f).ToString("F2") + "%";
            gdview_RecordList.Columns[gdview_RecordList.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        /// <summary>
        /// 重置搜索信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Reset_Click(object sender, EventArgs e)
        {
            ResetData();
        }

        /// <summary>
        /// 导出数据文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Export_Click(object sender, EventArgs e)
        {
            try
            {
                if (gdview_RecordList.Rows.Count > 0)
                {
                    ExcelHelper.ExportToCSV(gdview_RecordList);
                }
                else
                {
                    MessageBox.Show("未查询出数据，无法导出!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品测试记录，btn_Export_Click->{ex.Message}");
            }

        }

        /// <summary>
        /// 设置鼠标悬浮行的背景和前景颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_RecordList_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                gdview_RecordList.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.AliceBlue;
            }
        }

        /// <summary>
        /// 鼠标离开时恢复默认颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_RecordList_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                gdview_RecordList.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
            }
        }

        /// <summary>
        /// 选中不改变前景色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Gdview_RecordList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor;
        }

    }
}
